import React from 'react';
import PropTypes from 'prop-types';
import pathToRegexp from 'path-to-regexp';
import {Link} from 'dva/router';
import {Breadcrumb, Icon} from 'antd';
import {queryArray} from '../../utils/utils';
import styles from './CBreadcrumb.less';

const CBreadcrumb = ({location, mainNavList, withHome}) => {

  // get current nav
  let currentNavItem;
  for (let item of mainNavList) {
    if (item.path && pathToRegexp(item.path).exec(location.pathname)) {
      currentNavItem = item;
      break;
    }
  }

  // 递归 get pathArray
  let pathArray = [];
  const getPathArray = (item) => {
    pathArray.unshift(item);
    if (item.pid) {
      getPathArray(queryArray(mainNavList, item.pid, 'id'));
    }
  };

  // get paramMap
  let paramMap = {};
  if (!currentNavItem) {
    pathArray.push(mainNavList[0] || {
      id: 1,
      icon: 'laptop',
      name: 'Dashboard',
    });
    pathArray.push({
      id: 404,
      name: 'Not Found',
    });
  } else {
    getPathArray(currentNavItem);

    let keys = [];
    let values = pathToRegexp(currentNavItem.path, keys).exec(location.pathname.replace('#', ''));
    if (keys.length) {
      keys.forEach((currentNavItemValue, i) => {
        if (typeof currentNavItemValue.name !== 'string') {
          return;
        }
        paramMap[currentNavItemValue.name] = values[i + 1];
      })
    }
  }

  const breadcrumbs = pathArray.map((item, key) => {
    const content = (
      <span>{item.icon ? <Icon type={item.icon} style={{marginRight: 4}}/> : ''}{item.name}</span>
    );
    return (
      <Breadcrumb.Item key={key}>
        {((pathArray.length - 1) !== key) && item.path
          ? <Link to={pathToRegexp.compile(item.path)(paramMap)}>{content}</Link>
          : content}
      </Breadcrumb.Item>
    );
  });

  return (
    <Breadcrumb className={styles.breadcrumb}>
      {withHome && <Breadcrumb.Item href="/">
        <Icon type="home" style={{marginRight: 4}}/>
        <span>首页</span>
      </Breadcrumb.Item>}
      {breadcrumbs}
    </Breadcrumb>
  );
};

CBreadcrumb.propTypes = {
  location: PropTypes.object,
  mainNavList: PropTypes.array,
  withHome: PropTypes.object,
};

export default CBreadcrumb;
